package com.cet.algorithm.回溯.全排列;

import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @program: cet-practice
 * @description: 全排列2，可能包含重复元素
 * @author: 陈恩涛
 * @create: 2023-06-02 12:13
 **/
public class LC47 {

    List<List<Integer>> result = new LinkedList<>();

    Deque<Integer> path = new LinkedList<>();

    boolean[] used;

    public List<List<Integer>> permuteUnique(int[] nums) {
        used = new boolean[nums.length];
        // ！！！！！别忘了排序
        Arrays.sort(nums);
        backTracing(nums);
        return result;
    }

    public void backTracing(int[] nums) {
        // 递归终止条件
        if (path.size() == nums.length) {
            result.add(new LinkedList<>(path));
            return;
        }

        // 单层递归逻辑
        // 遍历修改需要使用iterator

        for (int i = 0; i < nums.length; i++) {
            if (used[i]) {
                continue;
            }

            // 树层去重
            if (i > 0 && nums[i] == nums[i - 1] && !used[i -1]) {
                continue;
            }

            path.add(nums[i]);
            used[i] = true;
            backTracing(nums);
            used[i] = false;
            path.removeLast();
        }
    }

    public static void main(String[] args) {
        LC47 lc47 = new LC47();
        System.out.println(lc47.permuteUnique(new int[]{3, 3, 0, 3}));
    }
}
